package com.fita.admin.service.agent.impl;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.fita.admin.dao.AgentAuditDao;
import com.fita.admin.dao.CouponDao;
import com.fita.admin.dao.PrincipalDao;
import com.fita.admin.entity.search.agent.AgentAuditSearch;
import com.fita.admin.entity.security.Login;
import com.fita.admin.handler.SmsHandler;
import com.fita.admin.service.DataServiceImpl;
import com.fita.admin.service.agent.AgentAuditService;
import com.fita.admin.web.Constant;
import com.fita.entity.agent.*;
import com.fita.entity.coupon.Coupon;
import com.fita.entity.coupon.CouponStatus;
import com.fita.entity.principal.District;
import com.fita.entity.principal.Principal;
import com.fita.entity.wallet.UserWallet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 
 * @author 宋剑宏
 *
 */
@Service("agentAuditService")
public class AgentAuditServiceImpl extends DataServiceImpl<AgentApply> implements AgentAuditService {

    private static final Logger logger = LoggerFactory.getLogger(AgentAuditServiceImpl.class);
	
	@Dao
	private CouponDao couponDao;

    @Dao
    private AgentAuditDao agentAuditDao;
    
    @Dao
    private PrincipalDao principalDao;

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    @Autowired
    private SmsHandler smsHandler;

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentAuditService#count(com.fita.entity.agent.
     * AgentApplyStatus)
     */
    public int count(AgentApplyStatus status, Login login) {
        if (status != null) {
                if(login.isAdmin()) {
                    if(status.equals(AgentApplyStatus.FINISHED)) {
                        return agentAuditDao.countAll(status);
                    } else {
                        return agentAuditDao.count(status);
                    }
                } else if(login.isSaleDirector()) {
                    if(status.equals(AgentApplyStatus.FINISHED)) {
                        return agentAuditDao.countAll(login.getDistrict(), status);
                    } else {
                        return agentAuditDao.count(login.getDistrict(), status);
                    }
                } else {
                    if(status.equals(AgentApplyStatus.FINISHED)) {
                        return agentAuditDao.countAll(status, login.getId());
                    }
                        return agentAuditDao.count(status, login.getId());
                }
        }
        return 0;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.fita.admin.service.agent.AgentAuditService#list(com.fita.entity.agent.
     * AgentApplyStatus, com.demo2do.core.entity.page.Page)
     */
    public List<AgentApply> list(AgentApplyStatus status, Page page, Login login) {
            if(login.isAdmin()) {
                if(status.equals(AgentApplyStatus.FINISHED)) {
                    List<AgentApply> agentApplie = agentAuditDao.list(status, page.getBeginIndex(), page.getEveryPage());
                    page.calculate();
                    return agentApplie;
                }else {
                    List<AgentApply> agentApplie = agentAuditDao.listAll(status, page.getBeginIndex(), page.getEveryPage());
                    page.calculate();
                    return agentApplie;
                }
            }else if(login.isSaleDirector()) {
                if(status.equals(AgentApplyStatus.FINISHED)) {
                    List<AgentApply> agentApplie = agentAuditDao.listAll(status, page.getBeginIndex(), page.getEveryPage(), login.getDistrict());
                    page.calculate();
                    return agentApplie;
                }
                    List<AgentApply> agentApplie = agentAuditDao.list(status, page.getBeginIndex(), page.getEveryPage(), login.getDistrict());
                    page.calculate();
                    return agentApplie;
            }  else {
                if(status.equals(AgentApplyStatus.FINISHED)) {
                    List<AgentApply> agentApplie = agentAuditDao.listAlls(status, page.getBeginIndex(), page.getEveryPage(), login.getId());
                    page.calculate();
                    return agentApplie;
                }
                    List<AgentApply> agentApplie = agentAuditDao.lists(status, page.getBeginIndex(), page.getEveryPage(), login.getId());
                    page.calculate();
                    return agentApplie;
        }
    }

    /* (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#count(com.fita.admin.entity.search.agent.AgentAuditSearch)
     */
    public int count(AgentAuditSearch search, Login login) {
        if(login.isAdmin()) {
            if(search.getStatus().equals(AgentApplyStatus.FINISHED)) {
                String sentence = search.buildSentenceTemplates();
                Map<String, Object> parameters = search.buildParameters();
                return genericDaoSupport.count(sentence, parameters);
            }
                String sentence = search.buildSentenceTemplate();
                Map<String, Object> parameters = search.buildParameters();
                return genericDaoSupport.count(sentence, parameters);
        }else if(login.isSaleDirector()){
           if(search.getStatus().equals(AgentApplyStatus.FINISHED)) {
                search = search.setDistrictID(login.getDistrict().getId());
                String sentence = search.buildSentenceTemplates();
                Map<String, Object> parameters = search.buildParameters();
                return genericDaoSupport.count(sentence, parameters);
           }
                   search = search.setDistrictID(login.getDistrict().getId());
                   String sentence = search.buildSentenceTemplate();
                   Map<String, Object> parameters = search.buildParameters();
                   return genericDaoSupport.count(sentence, parameters);
        } else {
            if(search.getStatus().equals(AgentApplyStatus.FINISHED)) {
                search = search.setPrincipalIds(login.getId());
                String sentence = search.buildSentenceTemplates();
                Map<String, Object> parameters = search.buildParameters();
                return genericDaoSupport.count(sentence, parameters);
            }
                search = search.setPrincipalIds(login.getId());
                String sentence = search.buildSentenceTemplate();
                Map<String, Object> parameters = search.buildParameters();
                return genericDaoSupport.count(sentence, parameters);
        }
    }

    /* (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#search(com.fita.admin.entity.search.agent.AgentAuditSearch, com.demo2do.core.entity.page.Page)
     */
    @SuppressWarnings("unchecked")
    public List<AgentApply> search(AgentAuditSearch search, Page page, Login login) {
        if(login.isAdmin()) {
            if(search.getStatus().equals(AgentApplyStatus.FINISHED)) {
                String sentence = search.buildSentenceTemplates();
                Map<String, Object> parameters = search.buildParameters();
                List<AgentApply> list = genericDaoSupport.searchForList(sentence, parameters, page.getBeginIndex(), page.getEveryPage());
                page.calculate();
                return list;
            }
                String sentence = search.buildSentenceTemplate();
                Map<String, Object> parameters = search.buildParameters();
                List<AgentApply> list = genericDaoSupport.searchForList(sentence, parameters, page.getBeginIndex(), page.getEveryPage());
                page.calculate();
                return list;
        }else if(login.isSaleDirector()){
            if(search.getStatus().equals(AgentApplyStatus.FINISHED)) {
                search = search.setDistrictID(login.getDistrict().getId());
                String sentence = search.buildSentenceTemplates();
                Map<String, Object> parameters = search.buildParameters();
                List<AgentApply> list = genericDaoSupport.searchForList(sentence, parameters, page.getBeginIndex(), page.getEveryPage());
                page.calculate();
                return list;
            }
                search = search.setDistrictID(login.getDistrict().getId());
                String sentence = search.buildSentenceTemplate();
                Map<String, Object> parameters = search.buildParameters();
                List<AgentApply> list = genericDaoSupport.searchForList(sentence, parameters, page.getBeginIndex(), page.getEveryPage());
                page.calculate();
                return list;
        } else {
            if(search.getStatus().equals(AgentApplyStatus.FINISHED)) {
                search = search.setPrincipalIds(login.getId());
                String sentence = search.buildSentenceTemplates();
                Map<String, Object> parameters = search.buildParameters();
                List<AgentApply> list = genericDaoSupport.searchForList(sentence, parameters, page.getBeginIndex(), page.getEveryPage());
                page.calculate();
                return list;
            }
                search = search.setPrincipalIds(login.getId());
                String sentence = search.buildSentenceTemplate();
                Map<String, Object> parameters = search.buildParameters();
                List<AgentApply> list = genericDaoSupport.searchForList(sentence, parameters, page.getBeginIndex(), page.getEveryPage());
                page.calculate();
                return list;
        }
    
    }


    /* (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#reject(java.lang.Long)
     */
    public void reject(Long id) {
        
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        
        genericDaoSupport.update(agentApply.reject());
        
    }


    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#activate(java.lang.Long)
     */
    public void activate(Long id) {
        
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        
        genericDaoSupport.update(agentApply.activate());
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#verified(java.lang.Long)
     */
    public void verified(Long id) {
        //8元优惠券
    	long templateId1=1;
    	//10元优惠券
    	long templateId2=2;
        //30元优惠券
    	long templateId3=3;
    	Coupon coupon1 = couponDao.loadSingleCoupon(CouponStatus.UNCLAIMED,templateId1);
    	List<Coupon> coupons2 = couponDao.loadManyCoupon(CouponStatus.UNCLAIMED,templateId2,0,2);
    	List<Coupon> coupons3 = couponDao.loadManyCoupon(CouponStatus.UNCLAIMED,templateId3,0,2);
    	
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);

        Agent agent = agentAuditDao.loadAgentByMobile(agentApply.getMobile());

        if (agent != null){
            throw new BusinessException("500", "代理手机号重复");
        }

        String companyName = agentApply.getCompanyName();
        AgentCompany agentCompany = agentApply.generateAgentCompany();
        //公司代理
        if(agentApply.getType().equals(AgentType.COMPANY)) {
                    //companyid是否为空
            if(agentApply.getCompanyId() == null) {   
                        //公司名字是否为空
                if(agentApply.getCompanyName() == null) {
                    throw new BusinessException("公司不可为空！");
                }else {
                    AgentCompany agentCompanyd = agentAuditDao.load(companyName);
                    //公司是否重复
                    if (agentCompanyd != null) {
                         throw new BusinessException("公司名称不可重复！");
                    } else {
                        //创建公司
                        genericDaoSupport.save(agentCompany.create());
                        Agent agents = new Agent(agentApply, agentCompany);
                        //创建代理人
                        genericDaoSupport.save(agents);
                        
                        //发放优惠券
                        if(coupon1 != null && coupons2 != null && coupons3 != null ) {

                            logger.info("userId [{}] mobile [{} coupon1 name [{}]",agents.getId(), agents.getMobile(),coupon1.getTemplate().getName());
                        	
                        	//优惠券1
                            genericDaoSupport.update(coupon1.identify(agents.getId(), agents.getMobile(),agents.getName()));
                            
                            genericDaoSupport.update(coupon1.getBatch().editClaimedAmount());

                            logger.info("userId [{}] mobile [{} coupon1 name [{}]",agents.getId(), agents.getMobile(),coupon1.getTemplate().getName());
                        	
                            for(Coupon coupon : coupons2) {
                            	//优惠券2  两张
                                genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(),agents.getName()));
                                
                                genericDaoSupport.update(coupon.getBatch().editClaimedAmount());

                                logger.info("userId [{}] mobile [{} coupon2 name [{}]",agents.getId(), agents.getMobile(),coupon.getTemplate().getName());
                            }
                        	
                            
                            for(Coupon coupon : coupons3) {
                            	  //优惠券3 两张
                                genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(),agents.getName()));
                                
                                genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                                logger.info("userId [{}] mobile [{} coupon3 name [{}]",agents.getId(), agents.getMobile(),coupon.getTemplate().getName());
                            }
                        }
                        
                    }
                } 
            }else {
                //如果companyId不为空,创建代理人
                AgentCompany agentCompanys = genericDaoSupport.load(AgentCompany.class, agentApply.getCompanyId());
                Agent agents = new Agent(agentApply, agentCompanys); 
                genericDaoSupport.save(agents);
                
                //发放优惠券
                if(coupon1 != null && coupons2 != null && coupons3 != null ) {
                	
                	//优惠券1
                    genericDaoSupport.update(coupon1.identify(agents.getId(), agents.getMobile(),agents.getName()));
                    
                    genericDaoSupport.update(coupon1.getBatch().editClaimedAmount());
                	
                    for(Coupon coupon : coupons2) {
                    	//优惠券2  两张
                        genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(),agents.getName()));
                        
                        genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                    }
                	
                    
                    for(Coupon coupon : coupons3) {
                    	  //优惠券3 两张
                        genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(),agents.getName()));
                        
                        genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                    }
                    
                }
            }

        }else {

            //个人代理
            genericDaoSupport.save(agentCompany.create());
            agentCompany.bingPrimaryAgent(agentApply.getPrimaryAgent(), agentApply.getRate());
            genericDaoSupport.update(agentCompany);
            Agent agents = new Agent(agentApply, agentCompany);
            genericDaoSupport.save(agents);

            UserWallet userWallet = new UserWallet(agentCompany);

            genericDaoSupport.save(userWallet);
            
            //发放优惠券
            if(coupon1 != null && coupons2 != null && coupons3 != null ) {
            	
            	//优惠券1
                genericDaoSupport.update(coupon1.identify(agents.getId(), agents.getMobile(),agents.getName()));
                
                genericDaoSupport.update(coupon1.getBatch().editClaimedAmount());
            	
                for(Coupon coupon : coupons2) {
                	//优惠券2  两张
                    genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(),agents.getName()));
                    
                    genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                }
            	
                
                for(Coupon coupon : coupons3) {
                	  //优惠券3 两张
                    genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(),agents.getName()));
                    
                    genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                }
            	
            }
            
        }
        genericDaoSupport.update(agentApply.verified());
        String content = "【"+ Constant.SMS_ORDER_COMPANY_NAME +"】尊敬的用户，您的飞腾会会员已经注册成功。海外自驾就选飞腾会：www.fita-club.com" ;
        smsHandler.sendAuditSuccessMessage(agentApply.getMobile(),content);

    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#edit(com.fita.entity.agent.AgentApply, java.lang.Long)
     */
    public void edit(Long id, AgentApply agentApply) {
        
        List<AgentApply> loads = agentAuditDao.loads(agentApply.getMobile());
        
        for (AgentApply inAgentApply : loads) {
            
            if (StringUtils.equals(inAgentApply.getMobile(), agentApply.getMobile()) && inAgentApply.getId() != id) {
                
                throw BusinessException.newInstance("400", "手机号不可重复！");
            }
        }
        AgentApply load = genericDaoSupport.load(AgentApply.class, id);
        
        if (agentApply.getType().isPersonal()) {
            
            load.clearCompanyInformation();
        }
        genericDaoSupport.update(load.edit(agentApply));
    }
        
    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#principal(java.lang.Long)
     */
    public void principal(Long id, Long principalId) {
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        Principal principal = genericDaoSupport.load(Principal.class, principalId);
        genericDaoSupport.update(agentApply.principal(principal));
        
    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#list(com.fita.admin.entity.security.Login)
     */
    public List<Principal> list(Login login, Page page, Long districtId) {
            //如果是销售主管，根据分区进行查询销售
        if(login.isSaleDirector()) {
            
            return principalDao.list("SALE_USER", login.getDistrict(), page.getBeginIndex(), page.getMaxResultRecords());
        }else {
            //如果是admin根据所选代理人的分区，查询销售
            return agentAuditDao.list(districtId);
        }
    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#district(java.lang.Long)
     */
    public void district(Long id, Long districtId, AgentApplyStatus status) {
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        District district = genericDaoSupport.load(District.class, districtId);
        if(status.equals(AgentApplyStatus.AUTHING)) {
            genericDaoSupport.update(agentApply.District(district));
        }
                genericDaoSupport.update(agentApply.editDistrict(district));
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#editPrincipal(java.lang.Long)
     */
    public void editPrincipal(Long id, Long principalId) {
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        Principal principal = genericDaoSupport.load(Principal.class, principalId);
        genericDaoSupport.update(agentApply.editPrincipal(principal));
    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#frost(java.lang.Long)
     */
    public void frost(Long id) {
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        genericDaoSupport.update(agentApply.frost());
    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#activation(java.lang.Long)
     */
    public void activation(Long id) {
        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        genericDaoSupport.update(agentApply.activation());
        
    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#listAgentCompany()
     */
    public List<AgentCompany> listAgentCompany() {
        return agentAuditDao.listAgentCompany(AgentType.COMPANY);
    }

    /*
     * (non-Javadoc)
     * @see com.fita.admin.service.agent.AgentAuditService#assignCompany(java.lang.Long, java.lang.String)
     */
    public void assignCompany(Long id, Long companyId) {
        AgentApply load = genericDaoSupport.load(AgentApply.class, id);
        AgentCompany agentCompany = genericDaoSupport.load(AgentCompany.class, companyId);
        genericDaoSupport.update(load.assignCompany(agentCompany));
    }
    
}
